package cn.gailvlun.gll.presentation.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.Utils;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.connect.common.AssistActivity;
import com.umeng.commonsdk.UMConfigure;
import com.vanniktech.emoji.EmojiManager;
import com.vanniktech.emoji.ios.IosEmojiProvider;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import cn.gailvlun.gll.BuildConfig;
import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatlib.ChatClient2;
import cn.gailvlun.gll.listener.GroundListener;
import cn.gailvlun.gll.net.base.UploadInfoReq;
import cn.gailvlun.gll.pay.UniPay;
import cn.gailvlun.gll.presentation.login.CaptchaActivity;
import cn.gailvlun.gll.presentation.login.CompleteProfileActivity;
import cn.gailvlun.gll.presentation.login.ForgotPasswordActivity;
import cn.gailvlun.gll.presentation.login.LoginActivity;
import cn.gailvlun.gll.presentation.login.NewPasswordActivity;
import cn.gailvlun.gll.presentation.login.PhoneBindingActivity;
import cn.gailvlun.gll.presentation.login.RegisterActivity;
import cn.gailvlun.gll.presentation.login.SelectCountryCodeActivity;
import cn.gailvlun.gll.presentation.login.WelcomeActivity;
import cn.gailvlun.gll.presentation.splash.SplashActivity;
import cn.gailvlun.gll.util.BackgroundEvent;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.LogUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.jpush.android.api.JPushInterface;
import io.realm.Realm;
import rx_activity_result2.HolderActivity;
import rx_activity_result2.RxActivityResult;



public class App extends Application {

    private static App INSTANCE;

    public static App getInstance() {
        return INSTANCE;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        if (LeakCanary.isInAnalyzerProcess(this)) {
            
            
            return;
        }
        LeakCanary.install(this);
        

        INSTANCE = this;

        Utils.init(this);
        ToastUtil.setBgResource(R.drawable.bg_toast);

        
        UMConfigure.init(this, BuildConfig.UMENG_APP_KEY, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, null);
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        UMConfigure.setEncryptEnabled(!BuildConfig.DEBUG);

        Context context = getApplicationContext();
        
        String packageName = context.getPackageName();
        
        String processName = getProcessName(android.os.Process.myPid());
        
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        CrashReport.initCrashReport(getApplicationContext(), "f494140385", true);

        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(this);

        if (!IsEmpty.string(JPushInterface.getRegistrationID(this))) {
            UploadInfoReq uploadInfoReq = new UploadInfoReq();
            uploadInfoReq.setRegistration_id(JPushInterface.getRegistrationID(this));
            uploadInfoReq.setDevice_brand(Build.BRAND);




        }


        Realm.init(this);
        RxActivityResult.register(this);





        EmojiManager.install(new IosEmojiProvider());
        
        registerActivityLifecycleCallbacks(new GroundListener() {
            @Override
            public void onForeground(Activity activity) {
                EventBus.getDefault().post(new BackgroundEvent(false));
                LogUtil.d("onForeground: " + activity.getClass().getSimpleName());
                if (isNeedWS(activity)) {
                    ChatClient2.getInstance().connect();
                }
            }

            @Override
            public void onBackground(Activity activity) {
                EventBus.getDefault().post(new BackgroundEvent(true));
                if (ActivityUtils.getTopActivity().getClass() != HolderActivity.class) {
                    ChatClient2.getInstance().disconnect();
                }
            }
        });

        UniPay.init(BuildConfig.WECHAT_APP_ID);
    }

    
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    private boolean isNeedWS(Activity activity) {
        if (activity.getClass() == SplashActivity.class
                || activity.getClass() == LoginActivity.class
                || activity.getClass() == WelcomeActivity.class
                || activity.getClass() == CaptchaActivity.class
                || activity.getClass() == NewPasswordActivity.class
                || activity.getClass() == RegisterActivity.class
                || activity.getClass() == CompleteProfileActivity.class
                || activity.getClass() == SelectCountryCodeActivity.class
                || activity.getClass() == PhoneBindingActivity.class
                || activity.getClass() == ForgotPasswordActivity.class
                || activity.getClass() == AssistActivity.class) {
            return false;
        } else {
            return true;
        }
    }
}
